/*
 * Copyright (c) 2022 Kirky
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lingeringdream.luciole.slice;

import com.lingeringdream.luciole.ResourceTable;
import com.lingeringdream.luciole.helper.PreferencesHelper;
import com.lingeringdream.luciole.helper.ResourceHelper;
import com.lingeringdream.luciole.helper.album.AlbumHelper;
import com.lingeringdream.luciole.helper.camera.CameraHelper;
import com.lingeringdream.luciole.model.Permissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.element.VectorElement;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.utils.Point;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.List;

/**
 * 识别页面
 *
 * @author Kirky
 * @version 1.0
 * @date 2022/4/30
 */
public class IdentitySlice extends AbilitySlice {
    private static final int RESULT_OK = 204;
    private static final int REQUEST_CODE_CHOOSE = 1001;
    private static boolean CAMERA_PERMISSION = false;
    private static boolean FLASHLIGHT = false;
    private final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x0, IdentitySlice.class.getSimpleName());
    private CameraHelper cameraHelper;
    private PreferencesHelper preferencesHelper;
    private List<Uri> selected = new ArrayList<>();

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_slice_identify);
        preferencesHelper = PreferencesHelper.getInstance(getContext());
        CAMERA_PERMISSION = preferencesHelper.getBoolean(Permissions.CAMERA.getPerName());

        setStatusBar();
        initAlbum();
        initFlashlight();
        Image reduce = findComponentById(ResourceTable.Id_identify_reduce);
        reduce.setClickedListener(component -> terminate());
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        if (cameraHelper != null) {
            cameraHelper.release();
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData)  {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            selected = Matisse.obtainResult(resultData);
//            dataAbilityUri
            HiLog.info(TAG, "mSelected: " + selected);
        }

    }

    /**
     * 设置沉浸式状态栏
     */
    private void setStatusBar() {
        getWindow().setStatusBarVisibility(WindowManager.LayoutConfig.MOD_APPLICATION_OVERLAY);
        getWindow().setStatusBarColor(ResourceHelper.getColorInt(getContext(),
                ResourceTable.Color_black_thin_dark, 0x66000000));
        DisplayManager displayManager = DisplayManager.getInstance();
        Point realPoint = new Point();
        displayManager.getDefaultDisplay(getContext()).get().getRealSize(realPoint);
        Point point = new Point();
        displayManager.getDefaultDisplay(getContext()).get().getSize(point);
        int height = realPoint.getPointYToInt() - point.getPointYToInt();

        Component statusBar = new Component(getContext());
        statusBar.setLayoutConfig(new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_PARENT, height
        ));
        DirectionalLayout layout = findComponentById(ResourceTable.Id_identify_statusBar);

//        ShapeElement shapeElement = new ShapeElement(getContext(), ResourceTable.Graphic_bg_identify_black);
//        statusBar.setBackground(shapeElement);
        layout.addComponent(statusBar);
        initCamera(realPoint);
    }

    /**
     * 初始化相机页面
     */
    private void initCamera(Point point) {
        SurfaceProvider surfaceProvider = findComponentById(ResourceTable.Id_identify_surface);
        cameraHelper = new CameraHelper(getApplicationContext(),this,
                surfaceProvider, false, true);
        if (CAMERA_PERMISSION) {
            cameraHelper.init(getWindow(), point);
            Image takePhoto = findComponentById(ResourceTable.Id_identify_camera);
            takePhoto.setClickedListener(component -> {
                cameraHelper.takeSingle();
            });
        }
    }

    /**
     * 初始化相册
     */
    private void initAlbum() {
        Image album = findComponentById(ResourceTable.Id_identify_album);
        album.setClickedListener(component -> AlbumHelper.from(this)
                .choose(MimeType.ofImage())
                .capture(false)
                .countable(true)
                .maxSelectable(1)
                .thumbnailScale(0.85f)
                .imageEngine(new PicassoEngine())
                .forResult(REQUEST_CODE_CHOOSE));
    }

    /**
     * 初始化闪光灯
     */
    private void initFlashlight(){
        Image flashlight = findComponentById(ResourceTable.Id_identify_flashlight);
        flashlight.setClickedListener(component -> {
            if (cameraHelper != null) {
                if (FLASHLIGHT){
                    cameraHelper.closeFlashLight();
                    VectorElement element =new VectorElement(getContext(),ResourceTable.Graphic_ic_flashlight_off_filled);
                    flashlight.setImageElement(element);
                    FLASHLIGHT = false;
                }else {
                    cameraHelper.openFlashLight();
                    VectorElement element =new VectorElement(getContext(),ResourceTable.Graphic_ic_flashlight_on_filled);
                    flashlight.setImageElement(element);
                    FLASHLIGHT=true;
                }
            }else {
                HiLog.error(TAG,"[Init flashlight failed]\tcameraHelper is null!");
            }
        });
    }
}
